<template>
  <div class="customer-manage">
    <div class="title flex-between">
      <div class="flex flex-align-c">
        <c-tags
          :data="[
            {
              color: businessDirection === 1 ? 'blue' : 'orange',
              label: businessDirection === 1 ? '客户' : '供应商'
            }
          ]"
        ></c-tags>
        <div class="companyName inline">{{ form.companyName }}</div>
      </div>
      <c-button
        type="primary"
        size="small"
        @click="add"
        v-if="businessDirection === 1 && $verifyBtn('customerSelfQuotaAdd')"
        >添加额度</c-button
      >
      <c-button
        type="primary"
        size="small"
        @click="apply"
        v-if="businessDirection === 2"
        >申请额度</c-button
      >
    </div>
    <a-alert class="inline-b tip" type="warning" show-icon>
      <template slot="message">
        <span v-if="businessDirection === 1"
          >采购额度：您给客户的点价采购额度，有了采购额度，该客户才可以对您的报价进行点价采购！</span
        >
        <span v-else
          >采购额度：供应商给您的点价采购额度，有了采购额度，您才可以对该供应商的报价进行点价采购！</span
        >
      </template>
    </a-alert>
    <c-table
      :data="quotaData"
      :showPage="false"
      :columns="tableColumns"
      :showHeader="false"
      :reload="false"
      :loading="loading"
      size="small"
    >
      <template slot="handle" slot-scope="{ row }">
        <div class="handle">
          <c-button type="link" @click="updateQuota(row)">编辑</c-button>
          <a-popconfirm
            :title="'是否确认删除 ' + row.futuresContractCode + ' 的额度'"
            @confirm="delQuota(row)"
          >
            <c-button type="link">删除</c-button>
          </a-popconfirm>
        </div>
      </template>
    </c-table>
    <c-modal
      v-model="quotaVisible"
      :title="quotaTitle"
      :width="350"
      @ok="submit"
      @cancel="restData"
      :okLoading="okLoading"
      destroyOnClose
    >
      <c-form
        ref="form"
        v-model="form"
        :data="formData"
        :rules="formRules"
        :col="{ labelCol: { style: 'width: 100px' } }"
      >
        <template v-slot:quotaType>
          <span>采购额度</span>
        </template>
        <template v-slot:categoryCode>
          <c-category
            v-model="form.categoryCode"
            getItem
            @change="changeCategory"
            v-if="quotaTitle === '添加额度' || quotaTitle === '申请额度'"
          ></c-category>
          <span v-else>{{ editRow.categoryName }}</span>
        </template>
        <template v-slot:futuresContractCode>
          <c-futures
            v-model="form.futuresContractCode"
            v-if="quotaTitle === '添加额度' || quotaTitle === '申请额度'"
            :futuresCode="futureCode"
            :filterList="futureContractCodeFilterList"
            @change="futuresChange"
          />
          <span v-else>{{ editRow.futuresContractCode }}</span>
        </template>
        <template v-slot:creditAmount>
          <a-input-number
            v-model="form.creditAmount"
            :max="999999"
          ></a-input-number>
        </template>
      </c-form>
    </c-modal>
  </div>
</template>

<script>
import {
  updateCredit,
  getCustomerCredit,
  getProviderCredit,
  purchaseCredit,
  deleteCredit,
  queryCustomerQuotaByContract,
  querySupplierQuotaByContract
} from "@/api/quota";

const columns = [
  {
    title: "品种",
    dataIndex: "categoryName"
  },
  {
    title: "合约月",
    dataIndex: "futuresContractCode"
  },
  {
    title: "已用额度",
    dataIndex: "usedCredit"
  },
  {
    title: "可用额度",
    dataIndex: "availableCredit"
  }
];

const formData = [
  {
    label: "额度类型",
    slot: "quotaType"
  },
  {
    label: "添加对象",
    prop: "companyName",
    type: "text"
  },
  {
    label: "商品品种",
    prop: "categoryCode",
    slot: "categoryCode"
  },
  {
    label: "合约月",
    prop: "futuresContractCode",
    slot: "futuresContractCode"
  },
  {
    label: "已用额度",
    prop: "usedCredit",
    type: "text"
  },
  {
    label: "可用额度",
    prop: "availableCredit",
    type: "text"
  },
  {
    label: "增加额度",
    prop: "creditAmount",
    // type: "number",
    slot: "creditAmount"
  }
];

export default {
  props: {
    // 交易方向，1客户2供应商
    businessDirection: {
      type: Number
    },
    // 企业信息
    companyData: {
      type: Object
    }
  },
  data() {
    return {
      futureContractCodeFilterList: [], // 添加额度时，过滤已添加的合约月
      quotaData: [],
      quotaVisible: false,
      quotaTitle: null,
      futureCode: undefined,
      form: {
        categoryCode: [],
        futuresContractCode: undefined,
        usedCredit: 0,
        availableCredit: 0,
        companyName: undefined,
        creditAmount: undefined
      },
      formRules: {
        categoryCode: [
          { required: true, message: "请选择商品品种", trigger: "change" }
        ],
        futuresContractCode: [
          { required: true, message: "请选择合约月", trigger: "change" }
        ],
        creditAmount: [
          { required: true, message: "请输入增加额度", trigger: "change" }
        ]
      },
      formData,
      okLoading: false,
      editRow: {},
      loading: false
    };
  },
  computed: {
    tableColumns() {
      let c = JSON.parse(JSON.stringify(columns));
      if (this.businessDirection === 1) {
        c.push({
          title: "操作",
          width: 200,
          scopedSlots: { customRender: "handle" }
        });
      }
      return c;
    }
  },
  watch: {
    // 每次打开重新请求
    companyData() {
      this.getCreditList();
    }
  },
  methods: {
    changeCategory(val) {
      if (val.length !== 0) this.futureCode = val[val.length - 1].futureCode;
    },
    // 关闭时初始化数据
    restData() {
      this.futureContractCodeFilterList = [];
      this.form.futuresContractCode = undefined;
      this.form.categoryCode = [];
      this.form.usedCredit = 0;
      this.form.availableCredit = 0;
      this.form.creditAmount = undefined;
      this.okLoading = false;
    },
    // 获取选中合约月的额度信息
    futuresChange() {
      let params = {
        categoryId: this.form.categoryCode[this.form.categoryCode.length - 1],
        companyId: this.companyData.companyId,
        futuresContractCode: this.form.futuresContractCode
      };
      let setQuota = res => {
        this.form.availableCredit = res.availableCredit;
        this.form.usedCredit = res.usedCredit;
      };
      if (this.businessDirection === 1) {
        queryCustomerQuotaByContract(params).then(res => {
          setQuota(res);
        });
      } else {
        querySupplierQuotaByContract(params).then(res => {
          setQuota(res);
        });
      }
    },
    // 添加额度
    add() {
      this.futureContractCodeFilterList = this.quotaData.map(
        item => item.futuresContractCode
      ); // 过滤已添加额度的合约月
      this.quotaTitle = "添加额度";
      this.quotaVisible = true;
      this.form = {
        companyName: this.form.companyName,
        categoryCode: [],
        futuresContractCode: undefined,
        usedCredit: 0,
        availableCredit: 0,
        creditAmount: undefined
      };
    },
    // 申请额度
    apply() {
      this.quotaTitle = "申请额度";
      this.quotaVisible = true;
      this.form = {
        companyName: this.form.companyName,
        categoryCode: [],
        futuresContractCode: undefined,
        usedCredit: 0,
        availableCredit: 0,
        creditAmount: undefined
      };
    },
    // 编辑额度
    updateQuota(row) {
      this.editRow = row;
      this.quotaTitle = "编辑额度";
      this.quotaVisible = true;
      this.form.categoryCode = row.categoryId;
      this.form.futuresContractCode = row.futuresContractCode;
      this.form.availableCredit = row.availableCredit;
      this.form.usedCredit = row.usedCredit;
      this.form.creditAmount = undefined;
    },
    // 删除额度
    delQuota(row) {
      deleteCredit({
        creditId: row.id
      }).then(() => {
        this.$emit("updated");
        this.getCreditList();
        this.$message.success("删除成功");
      });
    },
    // 提交额度操作
    submit() {
      this.$refs.form.validated().then(() => {
        this.okLoading = true;
        if (this.quotaTitle === "申请额度") {
          purchaseCredit({
            categoryId: this.form.categoryCode[
              this.form.categoryCode.length - 1
            ],
            sellerCompanyId: this.companyData.companyId,
            futuresContractCode: this.form.futuresContractCode,
            requestCreditAmount: this.form.creditAmount
          })
            .then(() => {
              this.$emit("updated");
              this.getCreditList();
              this.quotaVisible = false;
              this.$message.success("操作成功");
            })
            .finally(() => {
              this.okLoading = false;
            });
        } else {
          let params = {
            categoryId:
              this.quotaTitle === "编辑额度"
                ? this.editRow.categoryId
                : this.form.categoryCode[this.form.categoryCode.length - 1],
            version: this.quotaTitle === "编辑额度" ? this.editRow.version : 0,
            companyId: this.companyData.companyId,
            futuresContractCode: this.form.futuresContractCode,
            creditAmount: this.form.creditAmount,
            businessDirection: this.businessDirection
          };
          // 编辑额度需传creditId
          if (this.quotaTitle === "编辑额度") {
            params.creditId = this.editRow.id;
          }
          updateCredit(params)
            .then(() => {
              this.$emit("updated");
              this.getCreditList();
              this.quotaVisible = false;
              this.$message.success("操作成功");
            })
            .finally(() => {
              this.okLoading = false;
            });
        }
      });
    },
    // 获取企业的额度信息
    getCreditList() {
      this.loading = true;
      if (this.businessDirection === 1) {
        // 获取客户的额度信息
        getCustomerCredit({
          companyId: this.companyData.companyId
        })
          .then(res => {
            this.quotaData = res.companyCredit;
            this.form.companyName = res.companyName;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        // 获取供应商的额度信息
        getProviderCredit({
          companyId: this.companyData.companyId
        })
          .then(res => {
            this.quotaData = res.companyCredit;
            this.form.companyName = res.companyName;
          })
          .finally(() => {
            this.loading = false;
          });
      }
    }
  },
  created() {
    this.getCreditList();
  }
};
</script>

<style lang="scss" scoped>
.tip {
  margin: 18px 0;
}
.customer-manage {
  min-height: 271px;
  max-height: 600px;
  .title {
    .companyName {
      font-weight: bold;
      font-size: 17px;
      padding-right: 11px;
    }
  }
}
</style>
